//
//  QCViewController.swift
//  MM
//
//  Created by liujianlong on 2022/8/1.
//

import UIKit
import SnapKit
import TCCKit

class QCViewController: CCViewController {
    var connectStatus : BLEStatus = .normal
    var bytes = [UInt8]()
    var recived = true
    ///状态参数上报(0.5S周期上报)
    var base_info = [UInt8]()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let hidden = className == "QCHomeViewController" || className == "QCControlViewController" || className == "QCSettingViewController"
        navigationController?.setNavigationBarHidden(hidden, animated: animated)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    override func initData(){
        BLEData.appSetDataToPer(AIQC.userInfo.cmd,"00").write
    }
    
    deinit{
        NotifyTool.remove(self)
    }
}


//MARK: - 键盘相关通知
extension QCViewController{
    @objc override func addNotify(){
        super.addNotify()
        NotifyTool.add(self, #selector(methodConnectStatus), BLEStatusUpdateNotifyName)
        NotifyTool.add(self, #selector(methodBleData), BLEData.getDataFromPer.cmd)
    }
    
    @objc func methodConnectStatus(){
        connectStatus = BLE.status
        // if self.className != self.currentVC().className {return}
        switch BLE.status{
        case .connectedSucces:
            BLE.delegate = BleDataTool.share
            BLEData.checkFirmwareInfo.write
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { [weak self] in
                self?.initData()
            }
            if self.currentVC().className == "QCAlertPopViewController"{
                self.currentVC().dismiss(animated: false)
                return
            }
            CCHud.start("连接成功", stopTime: 1)
            APP.mcuArray.removeAll()
        case .didDiscoverCharacteristics:
            // BLEData.checkFirmwareInfo.write
            break
        case .disconnect:
            if BLE.connectedPeripherals.count > 0 {return}
            APP.mcuArray.removeAll()
            CCHud.start("断开连接", stopTime: 1)
        default:
            break
        }
    }
    
    @objc func methodBleData(_ notify:Notification){
        guard let userinfo = notify.userInfo as? [String:[UInt8]] else{return}
        guard let bytes = userinfo["data"] else{return}
        
        guard bytes.count >= 8, bytes[0...2].map({String(format:"%.2X",$0)}).joined() == "7FFAAF"else{return}
        let ack = bytes[7]
        
        if ack == UInt8(AIQC.infoStatus.ack){
            let stamp = Int64(Date().timeIntervalSince1970 * 1000)
            //            if BLE_stamp > 0 && stamp - BLE_stamp <= 500{
            //                return
            //            }
            BLE_stamp = 0
            let data = [UInt8](bytes[AI_index..<bytes.count])
            let mode = Int(data[0])
            let isCheckVC = currentVC().className == "QCCheckController"
            switch(mode, isCheckVC){
            case (1, false),///如果是自动检测模式，自动进入自动检测页面
                (2, false):///如果是手动检测模式，自动进入手动检测页面
                CCHud.stop()
                if !currentVC().isKind(of: UIAlertController.self) {
                    let vc = QCCheckController()
                    vc.isAuto = mode == 1
                    push(vc,true)
                }
            case (0, true),///如果当前页面是自动 ｜ 手动检测模式页面，当模式不是检测模式时候，需要自动退出页面
                (3, true):///如果当前页面是自动 ｜ 手动检测模式页面，当模式不是检测模式时候，需要自动退出页面
                //                backBtnAction()
                if currentVC().className == "QCCheckResultController"{return}
                navigationController?.popToRootViewController(animated: true)
            default:
                break
            }
            base_info = bytes
            deviceMode = DeviceMode(rawValue: Int(bytes[46]));
            //            deviceMode = DeviceMode(rawValue: 0);
            
        }else {
            let str = bytes.map{String(format:"%02X ", $0)}.joined()
            //            MyPrint("========== 通知 \(str)\n  \(self.className)")
            if ack == UInt8(AIQC.userInfo.ack){
                isPressureMode = bytes[8] == 1
            }
            self.bytes = bytes
        }
    }
}
